#encoding=utf-8
import xadmin,ujson,time,datetime,traceback
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
import websys.fun as fun
from django.db import transaction
from websys.models import (
    ServerInfo,EmailInfo,BlackList,GiftCode,Gift_Code,LogRecharge,Reply_Record,UserInfo,LogLogin
)
from  websys import (
    db_redis
)
#from user_two.models import LogRecharge
import json,os,random
from websys.api import InterfaceFun,ProtocolHelper,cbyx_InterfaceFun
from websys.view import cbyx_systemdata
import MySQLdb

class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)

PFINFO_LIST = []
#缓存平台列表
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()


URL2TITLE={'email':'邮件','forbid':'封号','speak':'禁言','gift_code':'激活码','recharge':'充值信息','reply':'玩家回复','get_data':'数据生成'}#,'info':'详细信息查询&修改','task':'付费任务完成率','system':'系统阶段统计&排行','resource':'资源排行','prop':'道具'}
#自定义的页面
URL2DEFINE=['email','forbid','speak','gift_code','recharge','reply','get_data']#,'task','system','resource','info','prop']

class CBYXManagerView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js','xadmin.widget.datetime.js')}

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)

    @csrf_protect_m
    def get(self, request,_type):
        # if not self.has_change_permission(request):
        #     raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonReportView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'cbyx_manager/blank.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl = 'cbyx_manager/%s.html' % (_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        self.htmldata={'type':_type,'apps':PFINFO_LIST}

        return self.get_response()

    def get_media(self):
        media = super(CBYXManagerView, self).get_media()
        #media.add_js((self.static('js/jquery.js'),))
        # media.add_css({'screen': ['css/jquery-ui.min.css']})
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(CBYXManagerView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

#ajax请求页面
urlpatterns = patterns('',
                        url(r'^email', 'websys.view.cbyx_otherdata.op_email', name='op_email'),
                        url(r'^em_quset', 'websys.view.cbyx_otherdata.op_emquset', name='op_quset'),
                        url(r'^forbid', 'websys.view.cbyx_otherdata.op_forbid', name='op_forbid'),
                        url(r'^fo_quset', 'websys.view.cbyx_otherdata.op_foquset', name='op_foquset'),
                        url(r'^fo_delete', 'websys.view.cbyx_otherdata.op_delete', name='op_delete'),
                        url(r'^speak', 'websys.view.cbyx_otherdata.op_speak', name='op_speak'),
                        url(r'^sp_delete', 'websys.view.cbyx_otherdata.op_spdelete', name='op_spdelete'),
                        url(r'^sp_quset', 'websys.view.cbyx_otherdata.op_spquset', name='op_spquset'),
                        url(r'^gift_code', 'websys.view.cbyx_otherdata.op_gift_code', name='op_gift_code'),
                        url(r'^gift_quset', 'websys.view.cbyx_otherdata.op_gift_quset', name='op_gift_quset'),
                        url(r'^recharge', 'websys.view.cbyx_otherdata.op_recharge', name='op_recharge'),
                        url(r'^reply_query', 'websys.view.cbyx_otherdata.op_reply_query', name='op_reply_query'),
                        url(r'^gm_reply', 'websys.view.cbyx_otherdata.op_gm_reply', name='op_gm_reply'),
                        url(r'^two_reply_query', 'websys.view.cbyx_otherdata.op_two_reply', name='op_two_reply'),
                        url(r'^get_data', 'websys.view.cbyx_otherdata.get_data', name='get_data'),
                       )

APP_KEY='nhmj_@12345'
import hashlib
#数字签名验证uid=xxx&gameid=xxx&sign=xxxx
def get_sorted_kv_list(param):
    sorted_keys = sorted(param)
    return [(k, param[k]) for k in sorted_keys]
def get_sign(param, ignore_keys=('sign'), app_key=APP_KEY):
    param = {k: str(v) for k, v in param.items() if k not in ignore_keys}
    kv_list = get_sorted_kv_list(param)
    string = "".join(["&".join(["=".join(x) for x in kv_list]), app_key])
    return hashlib.md5(string).hexdigest()

#获取多服务器
def getServers(obj):
    ser_arr=[]
    tmp_arr= obj.server.all()
    print '----------------',tmp_arr
    for ii_item in tmp_arr:
        ser_arr.append( ii_item.pf)
    return ser_arr


def create_gift_cdk(itemid, server_id, gift_type,code_num,actid,piciid,endtime,end_time):
    try:
        conn = MySQLdb.connect(host=webconfig.con_db['host'], port=webconfig.con_db['port'],
                               user=webconfig.con_db['user'], passwd=webconfig.con_db['password'],
                               db=webconfig.con_db['database'])
        cursor = conn.cursor()
        if int(gift_type)==0:
            for i in xrange(int(code_num)):
                cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
                #print '-----=-=-=-=-=-=-=-=-',cdk
                #print server_id,'========='
                while 1:
                    sqls="select * from t_gift_code where f_code=%s"%str(cdk)
                    cursor.execute(sqls)
                    data = cursor.fetchall()
                    if data:
                        cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
                        continue
                    else:
                        break
                if server_id:
                    sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_server_code, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
                    sql += "VALUES ( %s, 1, %s, '', %d, '%s', %d, %d,1, '%s');" % \
                           (str(piciid), server_id, int(endtime),str(itemid),int(gift_type),int(actid),str(cdk))
                else:
                    sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
                    sql += "VALUES ( %s, 1,'', %d, '%s', %d, %d,1, '%s');" % \
                           (str(piciid), int(endtime), str(itemid), int(gift_type), int(actid), str(cdk))
                cursor.execute(sql)
                gift_info = Gift_Code()
                gift_info.serial_no=piciid
                if server_id:
                    gift_info.server_code=server_id
                gift_info.expired_utc=end_time + ' 23:59:59'
                gift_info.items=itemid
                gift_info.gift_type=gift_type
                gift_info.activity_id=actid
                gift_info.gift_num=code_num
                gift_info.code=cdk
                gift_info.save()
        else:
            cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
            while 1:
                sqls = "select * from t_gift_code where f_code=%s" % str(cdk)
                cursor.execute(sqls)
                data = cursor.fetchall()
                if data:
                    cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
                    continue
                else:
                    break
            if server_id:
                sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_server_code, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
                sql += "VALUES ( %s, 1, %s, '', %d, '%s', %d, %d,%d, '%s');" % \
                       (str(piciid), server_id, int(endtime), str(itemid), int(gift_type), int(actid), int(code_num),str(cdk))
            else:
                sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
                sql += "VALUES ( %s, 1, '', %d, '%s', %d, %d,%d, '%s');" % \
                       (str(piciid), int(endtime), str(itemid), int(gift_type), int(actid), int(code_num),
                        str(cdk))

            gift_info = Gift_Code()
            gift_info.serial_no = piciid
            if server_id:
                gift_info.server_code = server_id
            gift_info.expired_utc = end_time + ' 23:59:59'
            gift_info.items = itemid
            gift_info.gift_type = gift_type
            gift_info.activity_id = actid
            gift_info.gift_num = code_num
            gift_info.code = cdk
            gift_info.save()
            cursor.execute(sql)
        conn.commit()
        conn.close()
        return 0
    except:
         return -1



from user_two.models import TServers
def get_server_status():
    server_info = TServers.objects.using('user_list').all()
    server_list=[]
    for i in server_info:
        if i.is_visible:
            server_list.append(i.server_code)
    return server_list

@csrf_exempt
@login_required(login_url="/xadmin/")
def op_email(request):
    data = {'ret': -1,'rows':[],'msg':''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server = servers[:-1].split(',')
    server_value=server[0]
    if len(server)==1 and server_value=='1':
        server=[]
        #filter_server =['_5wan1','test_mz','test2']
        server_info=ServerInfo.objects.all()
        status_server=get_server_status()
        for s in server_info:
            #if s.pf not in filter_server:
            if s.pf in status_server:
                server.append(s.pf)
    title =request.POST['title']
    content =request.POST['content']
    propid = request.POST['propid']
    txt_level = request.POST['txt_level']
    vip_level = request.POST['vip_level']
    arena_rank = request.POST['arena_rank']
    state=request.POST['state']
    print server,'------------------'
    if cbyx_InterfaceFun.gm_send_mail(server,uid,title,content,propid,int(state),txt_level,vip_level,arena_rank) == 0:
        data['ret']=-1
        data['msg']='发送邮件不成功'
        return HttpResponse(ujson.dumps(data))
    else:
        for ii in server:
             try:
                 with transaction.commit_on_success():
                    id=ServerInfo.objects.get(pf=ii)
                    email=EmailInfo()
                    email.title=title
                    email.content=content
                    email.uids=uid
                    email.propid=propid
                    email.state=state
                    le_dic ={'等级':None,'VIP等级':None,'竞技场':None}
                    le_dic['等级']=txt_level
                    le_dic['VIP等级']=vip_level
                    le_dic['竞技场']=arena_rank
                    email.arena=ujson.dumps(le_dic,ensure_ascii=False)
                    email.save()
                    email.server.add(id)
                    email.save()
             except:
                 data['msg'] = '发送服务器成功,写入记录失败!'
                 data['code'] =-1
                 return HttpResponse(ujson.dumps(data))
    data['ret'] = 0
    data['msg'] = '发送成功'
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_emquset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    state_dic = {1:'全服',2:'特定玩家',3:'特定等级范围'}
    email = EmailInfo.objects.all().order_by('-id')
    lists=[]
    for i in email:
        obj = {}
        obj['uids'] = i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['title'] = i.title
        obj['content'] = i.content
        obj['propid']=i.propid
        obj['state'] =None
        if i.state:
            obj['state']=state_dic[i.state]
        obj['create_time']=str(i.create_date)
        #c_dics={'level':'等级','VIPlevel':'vip等级','arena_rank':'竞技场等级'}
        #o_dics = eval(str(i.arena))
        #new_dics={}
        # for i in o_dics:
        #     if i in c_dics:
        #         new_dics[c_dics[i]]=o_dics[i]
        obj['levels']=i.arena
        lists.append(obj)
    data['ret'] = 0
    return HttpResponse(ujson.dumps(lists))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_forbid(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server = servers[:-1].split(',')

    if cbyx_InterfaceFun.gm_ban_login(server,uid,1) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
        return HttpResponse(ujson.dumps(data))
    else:
        for ii in server:
            try:
                with transaction.commit_on_success():
                    id = ServerInfo.objects.get(pf=ii)
                    black=BlackList()
                    black.uids=uid
                    black.status=0
                    black.operid=request.user.username
                    black.start_time=None
                    black.end_time=None
                    black.save()
                    black.server.add(id)
                    black.save()
            except:
                data['msg'] = '发送服务器成功,写入记录失败!'
                data['code'] =-1
                return HttpResponse(ujson.dumps(data))
        data['ret'] = 0
        data['msg'] = '发送成功'
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_foquset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    black = BlackList.objects.filter(status=0).order_by('-id')
    lists=[]
    for i in black:
        obj = {}
        obj['uids'] = i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['id']=i.id
        obj['operid']=i.operid
        lists.append(obj)
    data['ret'] = 0
    data['msg'] = '操作成功'
    return HttpResponse(ujson.dumps(lists))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_delete(request):
    data = {'ret': -1, 'msg': 'scuuess'}
    ids =request.POST['id']
    uid = request.POST['uid']
    servers = str(request.POST['server'])
    server = []
    server.append(servers)
    if cbyx_InterfaceFun.gm_ban_login(server,uid,0) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        try:
            with transaction.commit_on_success():
                BlackList.objects.get(id=int(ids)).delete()
        except:
            data['msg'] = '发送服务器(解封)成功,删除记录失败!'
            data['code'] = -1
            return HttpResponse(ujson.dumps(data))
    data['ret'] = 0
    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_prop(request):
    data = {'ret':-1,'msg':''}
    uid = request.POST['uid']
    server=request.POST['server']
    print '---------',server
    propid =request.POST['propid']
    number =request.POST['number']
    pr_list = str(propid).split(',')
    items ={}
    for i in pr_list:
        items[i]=number
    ser_arr = []
    ser_arr.append(server)
    print ser_arr,'=============='
    if InterfaceFun.DELITEMS(ser_arr,uid,items) ==0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        data['ret'] = 0
    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_speak(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server = servers[:-1].split(',')

    if cbyx_InterfaceFun.gm_ban_chat(server,uid,1) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        for ii in server:
            try:
                with transaction.commit_on_success():
                    id = ServerInfo.objects.get(pf=ii)
                    black=BlackList()
                    black.uids=uid
                    black.start_time=None
                    black.end_time=None
                    black.status=1
                    black.operid=request.user.username
                    black.save()
                    black.server.add(id)
                    black.save()
            except:
                data['msg'] = '发送服务器成功,写入记录失败!'
                data['code'] =-1
                return HttpResponse(ujson.dumps(data))
        data['ret'] = 0
        data['msg'] = '发送成功'
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_spquset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    black = BlackList.objects.filter(status=1).order_by('-id')
    lists=[]
    for i in black:
        obj = {}
        obj['uids'] = i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['id'] = i.id
        obj['operid']=i.operid
        lists.append(obj)
    data['ret'] = 0

    return HttpResponse(ujson.dumps(lists))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_spdelete(request):
    data = {'ret': -1, 'msg': 'scuuess'}
    ids =request.POST['id']
    uid = request.POST['uid']
    servers = str(request.POST['server'])
    server = []
    server.append(servers)
    if cbyx_InterfaceFun.gm_ban_chat(server,uid,0) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        try:
            with transaction.commit_on_success():
                BlackList.objects.get(id=int(ids)).delete()
        except:
            data['msg'] = '发送服务器(解除禁言)成功,删除记录失败!'
            data['code'] = -1
            return HttpResponse(ujson.dumps(data))
    data['ret'] = 0
    return HttpResponse(ujson.dumps(data))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_gift_code(request):
    data = {'ret': -1, 'msg': ''}
    itemid = request.POST['itemid']
    servers=str(request.POST['server'])
    if servers:
        server = servers[:-1].split(',')
        if len(server) >1:
            data['msg']='服务器禁止多选'
            return HttpResponse(ujson.dumps(data))
    if servers:
        server = servers[:-1].split(',')
        server_id = ServerInfo.objects.get(pf=server[0]).server_id
    else:
        server_id=''
    gift_type =request.POST['gift_type']
    code_num =request.POST['code_num']
    actid = request.POST['actid']
    piciid = request.POST['piciid']
    endtime = request.POST['endtime']
    end_utc = fun.TimeToStamp(endtime+' 23:59:59')
    if int(gift_type)==0:
        if int(code_num)>5000:
            data['msg']='数量超上限!'
            return HttpResponse(ujson.dumps(data))
    code=create_gift_cdk(itemid, server_id, gift_type, code_num, actid, piciid, end_utc,endtime)
    gift_info = GiftCode()
    gift_info.items=itemid
    gift_info.server_id=server_id
    gift_info.gift_type=gift_type
    gift_info.number=code_num
    gift_info.endtime=endtime
    gift_info.serial=piciid
    gift_info.activeid=actid
    if code==0:
        gift_info.save()
        data['msg']='生成成功!'
    else:
        data['msg']='生成失败!'
    data['ret']=code
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_gift_quset(request):
    data = {'ret': -1, 'msg': ''}
    gift_info = GiftCode.objects.all().order_by('-id')
    lists=[]
    for i in gift_info:
        dics={}
        dics['piciid']=i.serial
        dics['server']=i.server_id
        dics['itemids']=i.items
        dics['gift_type'] = i.gift_type
        dics['numbers'] = i.number
        dics['endtime'] = i.endtime
        dics['actid'] = i.activeid
        lists.append(dics)
    return HttpResponse(ujson.dumps(lists))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_recharge(request):
    t_date_0, t_date_1 = request.GET["date"].split(',')  # 日期
    s_id = request.GET["pf"]  # 服
    uid =request.GET["uid"]
    #server_id = ServerInfo.objects.get(pf=s_id).server_id
    #channel=list(eval(request.GET['channel']))
    t_date_start = t_date_0 + ' 00:00:00'
    t_date_end = t_date_1 + ' 23:00:00'
    #s_time = int(fun.TimeToStamp(t_date_start))
    #e_time = int(fun.TimeToStamp(t_date_end))
    #print s_time,'-------=--=-=-=-',e_time
    if uid:
        recharge_info = LogRecharge.objects.filter(server=s_id,create_time__range=(t_date_start,t_date_end),uid=uid).order_by('-id')
    else:
        recharge_info =LogRecharge.objects.filter(server=s_id,create_time__range=(t_date_start,t_date_end)).order_by('-id')
    lists=[]
    for i in recharge_info:
        re_dics = {}
        re_dics['uid']=i.uid
        re_dics['userid']=i.account
        re_dics['recharge']=i.money
        re_dics['retime']=str(i.create_time)
        lists.append(re_dics)
    return HttpResponse(ujson.dumps(lists))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_reply_query(request):
    lists= []
    data = {'ret': -1, 'msg': '','data':[]}
    uid = request.GET['uid']
    reply_dics = {0: '新消息', 1: '已查看',2:'已解决'}
    who_dics = {0: '该玩家', 1: 'GM'}
    if int(uid)==0:
        is_exist=[]
        reply_info = Reply_Record.objects.filter(is_reply__in=(0,1,2)).order_by('-create_time')
        for i in reply_info:
            if i.uid not in is_exist:
                reply_dic={}
                reply_dic['nickname']=i.nickname
                reply_dic['uid']=i.uid
                reply_dic['content']=i.content
                reply_dic['uids']=i.uid
                reply_dic['serverid']=i.serverid
                reply_dic['insert_time']=str(i.create_time)
                reply_dic['title']=i.title
                reply_dic['id']=i.id
                reply_dic['is_reply']=reply_dics[i.is_reply]
                reply_dic['is_who'] = who_dics[i.is_who]
                lists.append(reply_dic)
                is_exist.append(i.uid)
        return HttpResponse(ujson.dumps(lists))
    else:
        Reply_Record.objects.filter(uid=uid,is_reply=0).update(is_reply=1)
        reply_info = Reply_Record.objects.filter(uid=uid).order_by('-create_time')
        for i in reply_info:
            reply_dic={}
            reply_dic['nickname']=i.nickname
            reply_dic['uid']=i.uid
            reply_dic['content']=i.content
            reply_dic['insert_time']=str(i.create_time)
            reply_dic['id']=i.id
            reply_dic['serverid'] = i.serverid
            reply_dic['title'] = i.title
            reply_dic['is_reply']=reply_dics[i.is_reply]
            reply_dic['is_who'] = who_dics[i.is_who]
            reply_dic['oper']=i.oper
            lists.append(reply_dic)
        data['data']=lists
        data['msg']='success'
        data['ret']=0
        return HttpResponse(ujson.dumps(data))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_gm_reply(request):

    data={'ret':-1,'msg':''}
    id = request.POST['id']
    uid = request.POST['playid']
    nickname = request.POST['nickname']
    content = request.POST['content']
    title =request.POST['title']
    reply_title='GM回复'
    serverid=request.POST['serverid']
    server =[]
    server.append(serverid)
    if cbyx_InterfaceFun.gm_send_mail(server,uid,reply_title,content,'',2,'','','')==0:
        data['ret'] = -1
        data['msg'] = '发送邮件不成功'
        return HttpResponse(ujson.dumps(data))
    else:
        exist_info=Reply_Record.objects.filter(uid=uid,is_reply__in=(0,1))
        for i in exist_info:
            i.is_reply=2
            i.oper=request.user.username
            i.save()
        new_info = Reply_Record()
        new_info.uid=uid
        new_info.nickname=nickname
        new_info.content=content
        new_info.is_who=1
        new_info.title=title
        new_info.serverid=serverid
        new_info.oper=request.user.username
        new_info.save()
        data['ret']=0
        data['msg']='success'
        return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_two_reply(request):
    lists= []
    data = {'ret': -1, 'msg': '','data':[]}
    reply_dics = {0: '新消息', 1: '已查看', 2: '已解决'}
    who_dics = {0: '该玩家', 1: 'GM'}
    uid = request.GET['uids']
    date=request.GET['times']
    status = request.GET['statuss']
    if date:
        date_0, date_1 = str(date).split(',')
    reply_info=''
    if uid and date and status:
        reply_info = Reply_Record.objects.filter(uid=uid,is_reply=status,create_time__range=(date_0,date_1))
    elif uid and date and not status:
        reply_info = Reply_Record.objects.filter(uid=uid,create_time__range=(date_0, date_1))
    elif uid and status and not date:
        reply_info = Reply_Record.objects.filter(uid=uid, is_reply=status)
    elif status and date and not uid :
        reply_info = Reply_Record.objects.filter(is_reply=status, create_time__range=(date_0, date_1))
    elif uid and not status and not date:
        reply_info = Reply_Record.objects.filter(uid=uid)
    elif status and not date and not uid:
        reply_info = Reply_Record.objects.filter(is_reply=status)
    elif date and not uid and not status:
        reply_info = Reply_Record.objects.filter(create_time__range=(date_0, date_1))
    else:
        print uid,'<<<--',date,'<<<---',status
        data['msg']='error'
        return HttpResponse(ujson.dumps(data))
    for i in reply_info:
        reply_dic = {}
        reply_dic['nickname'] = i.nickname
        reply_dic['uid'] = i.uid
        reply_dic['content'] = i.content
        reply_dic['uids'] = i.uid
        reply_dic['serverid'] = i.serverid
        reply_dic['insert_time'] = str(i.create_time)
        reply_dic['title'] = i.title
        reply_dic['id'] = i.id
        reply_dic['is_reply'] = reply_dics[i.is_reply]
        reply_dic['is_who'] = who_dics[i.is_who]
        lists.append(reply_dic)
    data['data'] = lists
    data['msg'] = 'success'
    data['ret'] = 0
    return HttpResponse(ujson.dumps(data))





@csrf_exempt
@login_required(login_url="/xadmin/")
def get_data(request):
    data = {'ret': -1, 'msg': ''}
    servers = str(request.POST['server'])
    date = str(request.POST['date'])
    date1,date2=date.split(',')
    server = servers[:-1].split(',')

    def getdata(filename,servers):
        t_date_start = time.mktime(time.strptime(str(date1 + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))
        t_date_end = time.mktime(time.strptime(str(date2 + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))
        server_list = servers
        print 'server_list---------->>>', server_list
        b_date = t_date_start
        f = open("getdata/%s.txt" % str(filename), "w+")
        while b_date <= t_date_end:
            time_local = time.localtime(b_date)
            dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)

            dts = datetime.datetime.fromtimestamp(b_date)
            delta = datetime.timedelta(days=1)

            changed_time = dts + delta

            data_str = '%s' % str(dt.split(' ')[0]) + ' , '
            for server in server_list:
                re_number = 0
                recharge = LogRecharge.objects.filter(create_time__gte=dt, create_time__lt=changed_time, server=server)
                for i in recharge:
                    re_number += i.money
                recharge_count = recharge.distinct().values('uid').count()
                new_info = UserInfo.objects.filter(create_time__gte=dt, create_time__lt=changed_time, server=server)
                new_user_count = new_info.count()
                online_DAU_info = LogLogin.objects.filter(create_time__gte=dt, create_time__lt=changed_time,
                                                          server=server)
                online_count = online_DAU_info.distinct().values('uid').count()
                data_str += str(server)+' , ' + str(re_number) + ' , ' + str(new_user_count) + ' , ' + str(online_count) + ' , ' + str(
                    recharge_count) + ' , '

            if b_date == t_date_end:
                print dt, '--------time----'
            f.write(data_str + '\n')
            Unixtime = time.mktime(time.strptime(changed_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
            b_date = Unixtime
        f.close()
        print '=================success-------------'
        return 1

    file_name=datetime.datetime.now().date()
    status = getdata(file_name,server)
    if status==1:
        data['ret']=0
        data['msg']='success'
    return HttpResponse(ujson.dumps(data))

#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonReportView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonReportView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonReportView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonReportView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonReportView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonReportView,name='loadloss_report')
xadmin.site.register_view(r'^cbyx_otherdata/(.+)/$', CBYXManagerView,name='user_%s')#各种按日，月，年汇总页面
